/*
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2023-10-24 11:43:49
 * @LastEditors: huangtianyang
 * @LastEditTime: 2023-10-24 16:09:43
 * @FilePath: \cxl-h5\src\utils\compressImage.ts
 */
import { getBase64ImageSizeInKB } from './WXSdk'

export default class CompressImage {
    init(base64: string, callback = (base64: string) => {}, w = 1920) {
        const oImg = document.createElement('img')
        oImg.crossOrigin = ''
        oImg.src = base64
        oImg.onload = (res: any) => {
            const imgWidth = w
            const imgHeight = (w * Number(oImg.height)) / Number(oImg.width)
            const canvas = document.createElement('canvas')
            canvas.width = imgWidth
            canvas.height = imgHeight
            const ctx = canvas.getContext('2d')
            ctx?.drawImage(oImg, 0, 0, imgWidth, imgHeight)
            const str = canvas.toDataURL('image/jpeg', 1)
            console.log('图片大小', imgWidth, imgHeight, getBase64ImageSizeInKB(str).toFixed(1))
            if (getBase64ImageSizeInKB(str) >= 3 * 1024) {
                this.init(str, callback, 1000)
            } else {
                callback(str)
            }
        }
    }
}
